﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Primitives;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using Moonlite.ExtensionApi;
using Moonlite.Platform.General;
namespace Moonlite.Composition {
    public partial class ExtensionManagerForm : Form {
        public static ExtensionCollection Extensions { get; set; }
        private ExtensionCollection NotLoadedExtensions { get; set; }
        private List<string> SessionFilePaths { get; set; }
        public static SerializableDictionary PartsToBeRemoved { get; set; }

        public void AddAssemblyExtension(string path) {
            string extensionPath = String.Format("{0}\\{1}", Application.StartupPath, Path.GetFileName(path));
            if (File.Exists(extensionPath) == true) {
                return;
            }

            NotLoadedExtensions = new ExtensionCollection();
            File.Copy(path, extensionPath);
            SessionFilePaths.Add(extensionPath);
            NotLoadedExtensions.Add(new Extension(Path.GetFileName(extensionPath) + " (Will be loaded upon restart)", extensionPath));
            RefreshExtensions();
        }

        public void UpdateList() {
            if (Extensions == null) {
                Extensions = new ExtensionCollection();
            }

            Extensions.Clear();
            foreach (Assembly assembly in Global.Instance.ExtensionAssemblies) {
                Extensions.Add(new Extension(Path.GetFileName(assembly.GetPath()), Path.GetDirectoryName(assembly.GetPath())));
            }
            if (NotLoadedExtensions != null) {
                foreach (Extension extension in NotLoadedExtensions) {
                    Extensions.Add(extension);
                }
            }
        }

        public void RefreshExtensions() {
            UpdateList();
            extensionBindingSource.DataSource = Extensions;
        }

        private void OnBrowseClick(object sender, EventArgs e) {
            using (OpenFileDialog openFileDialog = new OpenFileDialog { Filter = "Dynamic Link Libraries (*.dll)|*.dll" }) {
                if (openFileDialog.ShowDialog() != DialogResult.OK) {
                    return;
                }

                AddAssemblyExtension(openFileDialog.FileName);
            }
        }

        private void OnCancelClick(object sender, EventArgs e) {
            SessionFilePaths.ForEach(path => {
                if (File.Exists(path) == true)
                    File.Delete(path);
            });

            Close();
        }

        private void OnOKClick(object sender, EventArgs e) {
            Close();
        }

        private void OnGridControlKeyUp(object sender, KeyEventArgs e) {
            if (gridControl.SelectedCells.Count > 0) {
                return;
            }

            if (e.KeyCode != Keys.Delete) {
                return;
            }

            if (((Extension)gridControl.SelectedRows[0].DataBoundItem).Name.IndexOf(" (Will be removed upon restart)") > -1) {
                return;
            }

            string path = ((Extension)gridControl.SelectedRows[0].DataBoundItem).Path;
            try {
                if (PartsToBeRemoved.ContainsKey(path) == false) {
                    PartsToBeRemoved.Add(path, true);
                }

                PartsToBeRemoved.WriteXml(Application.LocalUserAppDataPath + "\\Settings\\RemovedExtensions.xml");
                ((Extension)gridControl.SelectedRows[0].DataBoundItem).Name = ((Extension)gridControl.SelectedRows[0].DataBoundItem).Name + " (Will be removed upon restart)";
            }
            catch (Exception exception) {
                MessageBox.Show("Cannot access extension library. Please close all windows using the extenion library and try again. Inner exception: \r\n" + exception.Message,
                    "Moonlite Map Studio", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);

                return;
            }
        }

        public ExtensionManagerForm() {
            InitializeComponent();
            SessionFilePaths = new List<string>();
            RefreshExtensions();
        }
    }
}